package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"
	"net"

	"grpc-jwt-yonghurenzheng/jwt_grpc/config"
	pb "grpc-jwt-yonghurenzheng/jwt_grpc/proto"

	"google.golang.org/grpc"
)

type userServer struct {
	pb.UnimplementedUserServiceServer
}

func (s *userServer) GetUserProfile(ctx context.Context, req *pb.GetUserProfileRequest) (*pb.GetUserProfileResponse, error) {
	var username, email string
	err := config.DB.QueryRow("SELECT username, email FROM users WHERE id = ?", req.UserId).Scan(&username, &email)
	if err != nil {
		if err == sql.ErrNoRows {
			return nil, fmt.Errorf("用户ID %d 不存在", req.UserId)
		}
		return nil, fmt.Errorf("数据库查询失败: %v", err)
	}

	return &pb.GetUserProfileResponse{Id: req.UserId, Username: username, Email: email}, nil
}

func (s *userServer) DeleteUser(ctx context.Context, req *pb.DeleteUserRequest) (*pb.DeleteUserResponse, error) {
    // 实际项目中应加入事务处理
    // 此处简化，不处理外键关联
     // 执行删除操作
    res, err := config.DB.Exec("DELETE FROM users WHERE id = ?", req.UserId)
    if err != nil {
        return nil, fmt.Errorf("删除用户失败: %v", err)
    }

    // 检查是否有行被删除
    rows, err := res.RowsAffected()
    if err != nil {
        return nil, fmt.Errorf("检查删除结果失败: %v", err)
    }

    if rows == 0 {
        return nil, fmt.Errorf("用户不存在")
    }

    return &pb.DeleteUserResponse{Message: "用户删除成功"}, nil
}

func main() {
	config.InitDB()
	lis, err := net.Listen("tcp", ":50052") // 用户服务端口
	if err != nil {
		log.Fatalf("无法监听端口: %v", err)
	}
	s := grpc.NewServer()
	pb.RegisterUserServiceServer(s, &userServer{})
	fmt.Println("🚀 User gRPC Service 启动于 :50052")
	if err := s.Serve(lis); err != nil {
		log.Fatalf("gRPC 服务启动失败: %v", err)
	}
}